package LC;

public class 在排序数组中查找元素的第一个和最后一个位置 {
    public static int[] searchRange(int[] nums, int target) {
        return new int[]{left(nums,target),right(nums,target)};

    }
    static int left(int[] nums,int target){
      int left=0,right=nums.length-1;
      while (left<=right){
          int mid=left+(right-left)/2;
          if(nums[mid]<target){
              left=mid+1;
          }else if(nums[mid]>target){
             right=mid-1;
          }else if(nums[mid]==target){
              right=mid-1;
          }

      }
        if (left >= nums.length || nums[left] != target) {
            return -1;
        }
        return left;
    }
    static int right(int[] nums, int target) {
        int left = 0, right = nums.length - 1;
        while (left <= right) {
            int mid = left + (right - left) / 2;
            if (nums[mid] < target) {
                left = mid + 1;
            } else if (nums[mid] > target) {
                right = mid - 1;
            } else if (nums[mid] == target) {
                // 这里改成收缩左侧边界即可
                left = mid + 1;
            }
        }
        // 这里改为检查 right 越界的情况，见下图
        if (right < 0 || nums[right] != target) {
            return -1;
        }
        return right;
    }


    public static void main(String[] args) {
        int[] nums=new int[]{5,7,7,8,8,8,10};
        int[] result= searchRange(nums, 8);
        for(int i:result){
            System.out.println(i);
        }
    }
}
